using AdminApiTemplate.Cache;
using AdminApiTemplate.Common.Exceptions;
using AdminApiTemplate.Common.Helpers;
using AdminApiTemplate.Services.WorkWx;

namespace AdminApiTemplate.Tasks.WorkWx
{
    public class SendWorkWxTask : ITask
    {
        private readonly MySqlHelper _defaultQuery;

        private readonly WorkWxService _workWxService;

        public SendWorkWxTask(
            MySqlHelper defaultQuery)
        {
            _defaultQuery = defaultQuery;
            _workWxService = new WorkWxService(new MySql.Data.MySqlClient.MySqlConnection(_defaultQuery._connStr));
        }

        public void Execute()
        {
            var sql = "SELECT Id,ToUser,Content,Title,Url from queuesendworkwxmsg WHERE SendingStatus=1 AND (NotifyTime is null or NotifyTime<NOW())ORDER BY Id LIMIT 100";
            var items = _defaultQuery.GetList<SendWorkWxItem>(sql);
            if (items.Count == 0)
            {
                return;
            }

            var interval = ConfigHelper.GetSysConfig<int>("SendWorkWxInterval", 1000);
            var appId = ConfigHelper.GetSysConfig<string>("WorkWx:AppId", "");
            var secret = ConfigHelper.GetSysConfig<string>("WorkWx:AppSecret:KOLAdmin", "");
            var agentId = ConfigHelper.GetSysConfig<int>("WorkWx:AgentId:KOLAdmin", 0);

            var workWxHelper = new ThirdParty.WorkWx.WorkWxApiProxy(appId, secret);
            var token = _workWxService.GetAccessTokenAsync(appId).Result;
            if (string.IsNullOrEmpty(token))
            {
                var tokenResponse = workWxHelper.RealGetAccessTokenAsync().Result;
                if (tokenResponse != null)
                {
                    token = tokenResponse.access_token;
                    var update = _workWxService.UpdateAccessTokenAsync(appId, token, DateTime.Now.AddSeconds(tokenResponse.expires_in)).Result;
                }
            }

            sql=$"update queuesendworkwxmsg set SendingStatus=2,SendingTime=NOW() where Id in ({string.Join(",", items.Select(o => o.Id.GetValueOrDefault()))})";
            _defaultQuery.Execute(sql);

            for (var i = 0; i<items.Count; i++)
            {
                if (i > 0)
                {
                    var r = RandomHelper.Instance.Next(interval, interval+2000);
                    Thread.Sleep(r);
                }

                var item = items[i];
                if (string.IsNullOrEmpty(token))
                {
                    sql = $"update queuesendworkwxmsg set SendingStatus=4,Remark=@remark where Id={item.Id.GetValueOrDefault()}";
                    _defaultQuery.Execute(sql, new { remark = "发送失败，无法获取AccessToken" });
                    continue;
                }

                if (string.IsNullOrEmpty(item.ToUser))
                {
                    sql = $"update queuesendworkwxmsg set SendingStatus=4,Remark=@remark where Id={item.Id.GetValueOrDefault()}";
                    _defaultQuery.Execute(sql, new { remark = "发送失败，用户不正确" });
                    continue;
                }

                var remark = default(string);
                try
                {
                    ///文本卡片信息
                    workWxHelper.SendTextToUser(token, agentId, item.Content, item.Title, item.Url, item.ToUser.Split(","));

                    sql = $"update queuesendworkwxmsg set SendingStatus=3,Remark=null where Id={item.Id.GetValueOrDefault()}";
                    _defaultQuery.Execute(sql);
                }
                catch (WithCodeException wcex)
                {
                    remark = wcex.Message;
                }
                catch (Exception ex)
                {
                    remark = ex.Message;
                    LogHelper.Write(ex.ToString(), "SendWorkWx");
                }

                if (!string.IsNullOrEmpty(remark))
                {
                    sql = $"update queuesendworkwxmsg set SendingStatus=4,Remark=@remark where Id={item.Id.GetValueOrDefault()}";
                    _defaultQuery.Execute(sql, new { remark });
                }
            }
        }
    }

    public class SendWorkWxItem
    {
        /// <summary>
        /// Id
        /// </summary>
        public int? Id { get; set; }

        /// <summary>
        /// 发送给
        /// </summary>
        public string ToUser { get; set; }

        /// <summary>
        /// 内容
        /// </summary>
        public string Content { get; set; }
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 链接
        /// </summary>
        public string Url { get; set; }
    }
}
